﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Dropthings.Widget.Framework;
using Dropthings.Widget.Widgets;
using Dropthings.Widget.Widgets.FusionCharts;
using InfoSoftGlobal;
using Dropthings.Util;
using Dropthings.Business.Facade;
using Dropthings.Business.Facade.Context;
using System.Collections.Generic;
using System.Text;

public partial class FusionChart_ECLast3YearColum : System.Web.UI.UserControl, IWidget
{
    #region Fields

    private IWidgetHost _Host;
    private XElement _State;
    private XElement State
    {
        get
        {
            if (_State == null)
            {
                string stateXml = this._Host.GetState();
                if (string.IsNullOrEmpty(stateXml))
                {
                    _State = new XElement("state",
                        new XElement("year", DateTime.Now.Year.ToString()),
                        new XElement("orgnaziationCode", ""));
                }
                else
                {
                    _State = XElement.Parse(stateXml);
                }
            }
            return _State;
        }
    }


    public int ShowYear
    {
        get { return State.Element("year") == null ? DateTime.Now.Year : int.Parse(State.Element("year").Value); }
        set
        {
            if (State.Element("year") == null)
                State.Add(new XElement("year", value));
            else
                State.Element("year").Value = value.ToString();
        }
    }
    public string ShowBuildingCode
    {
        get { return State.Element("orgnaziationCode") == null ? string.Empty : State.Element("orgnaziationCode").Value; }
        set
        {
            if (State.Element("orgnaziationCode") == null)
                State.Add(new XElement("orgnaziationCode", value));
            else
                State.Element("orgnaziationCode").Value = value;
        }
    }

    #endregion Fields

    #region Methods

    void IEventListener.AcceptEvent(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

    void IWidget.Closed()
    {
    }

    void IWidget.Collasped()
    {
    }

    void IWidget.Expanded()
    {
    }

    void IWidget.HideSettings(bool userClicked)
    {
        SettingsPanel.Visible = false;
        this.ShowYear = int.Parse(YearDropDownList.SelectedValue);
        this.ShowBuildingCode = BuildingDropDownList.SelectedValue;
        this.SaveState();
    }

    void IWidget.Init(IWidgetHost host)
    {
        this._Host = host;
    }

    void IWidget.Maximized()
    {
    }

    void IWidget.Restored()
    {
    }

    void IWidget.ShowSettings(bool userClicked)
    {
        SettingsPanel.Visible = true;
        if (userClicked)
        {
            YearDropDownList.SelectedIndex = -1;
            YearDropDownList.Items.FindByText(this.ShowYear.ToString()).Selected = true;
            BuildingDropDownList.SelectedIndex = -1;
            if (BuildingDropDownList.Items.FindByValue(this.ShowBuildingCode)!=null)
                BuildingDropDownList.Items.FindByValue(this.ShowBuildingCode).Selected = true;
        }
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        Dictionary<string, DataSet> values = getDatas(ShowYear, ShowBuildingCode);
        strXML = new StringBuilder();
        strXML.Append("<chart caption='最近三年能源对比分析图'");
        strXML.Append(" xAxisName='月份' yAxisName='能耗(标煤)' showNames='1'");
        strXML.Append(" animation='1' showBorder='0'");
        strXML.Append(" useRoundEdges='1' bgColor='FFFFFF,FFFFFF'> decimals='2'");

        strXML.Append("<categories>");
        strXML.Append("<category label='一月' />");
        strXML.Append("<category label='二月' />");
        strXML.Append("<category label='三月' />");
        strXML.Append("<category label='四月' />");
        strXML.Append("<category label='五月' />");
        strXML.Append("<category label='六月' />");
        strXML.Append("<category label='七月' />");
        strXML.Append("<category label='八月' />");
        strXML.Append("<category label='九月' />");
        strXML.Append("<category label='十月' />");
        strXML.Append("<category label='十一月' />");
        strXML.Append("<category label='十二月' />");
        strXML.Append("</categories>");

        if (values.Keys.Count > 0)
        {
            foreach (string key in values.Keys)
            {
                strXML.AppendFormat("<dataset seriesName='{0}' >",key);
                DataSet keyValue = values[key];
                if (keyValue != null && keyValue.Tables.Count > 0 && keyValue.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in keyValue.Tables[0].Rows)
                    {
                        if (Convert.ToDouble(dr[1]) > 0 && Convert.ToDouble(dr[2]) > 0)
                            strXML.Append("<set value='" + (Convert.ToDouble(dr[1]) + Convert.ToDouble(dr[2])).ToString() + "' tooltext='年:" + key + "{br}电:" + dr[1].ToString() + "{br}气:" + dr[2].ToString() + "{br}'/>");
                        else
                            strXML.Append("<set value=''/>");

                    }
                }
                strXML.Append("</dataset>");
            }
        }
        strXML.Append("</chart>");
        Literal1.Text = FusionCharts.RenderChartHTML("../FusionCharts/ScrollColumn2D.swf", "", strXML.ToString(), "myFirst", "100%", "267", false, false);
    }

    protected void SaveSettings_Click(object sender, EventArgs e)
    {
        _Host.HideSettings(true);
    }

    StringBuilder strXML;
    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (YearDropDownList.Items.Count == 0)
        {
            for (int i = 2000; i <= DateTime.Now.Year; i++)
            {
                YearDropDownList.Items.Add(new ListItem(i.ToString()));
            }
        }
        
        if (BuildingDropDownList.Items.Count == 0)
        {
            Dictionary<string, string> allBuildings = getAllBuildings();
            foreach (string key in allBuildings.Keys)
            {
                ListItem item= new ListItem();
                item.Text = allBuildings[key];
                item.Value = key;
                BuildingDropDownList.Items.Add(item);
            }
            if (BuildingDropDownList.Items.Count > 0)
                this.ShowBuildingCode = BuildingDropDownList.Items[0].Value;
        }
        
    }

    private Dictionary<string, string> getAllBuildings()
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            Dictionary<string, string> allBuildings = new Dictionary<string, string>();
            DataSet ds = facade.GetOrganizeBaseInfo();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string name = Convert.ToString(dr["OrganizeName"]);
                    string key = Convert.ToString(dr["OrganizeIdentify"]);
                    allBuildings.Add(key, name);
                }
            }
            return allBuildings;
        }
    }

    private Dictionary<string, DataSet> getDatas(int year,string buildingCode)
    {
        Dictionary<string, DataSet> values=new Dictionary<string,DataSet>();
        DataSet ThisYearDatas = getMonthDatas(year, buildingCode);
        DataSet LastYearDatas = getMonthDatas(year-1, buildingCode);
        DataSet YearBeforeLastYearDatas = getMonthDatas(year-2, buildingCode);
        values.Add(year.ToString(), ThisYearDatas);
        values.Add((year - 1).ToString(), LastYearDatas);
        values.Add((year - 2).ToString(), YearBeforeLastYearDatas);
        return values;
    }

    private DataSet getMonthDatas(int year,string buildingCode)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetECYearDatas(buildingCode, year);
            return ds;
        }
    }

    private void SaveState()
    {
        var xml = this.State.Xml();
        this._Host.SaveState(xml);
        this._State = null;
    }
    #endregion Methods
}